package com.yctan.base.Interceptor;

import com.alibaba.druid.support.json.JSONUtils;
import com.yctan.base.annotation.PassToken;
import com.yctan.base.annotation.SuperAdmin;
import com.yctan.base.entity.Admin;
import com.yctan.base.entity.R;
import com.yctan.base.entity.Supplier;
import com.yctan.base.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;

@Component
public class AuthenticationInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception {
        // 如果不是映射到方法直接通过
        if (!(object instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) object;
        Method method = handlerMethod.getMethod();
        //检查是否有passtoken注释，有则跳过认证
        if (method.isAnnotationPresent(PassToken.class)) {
            PassToken passToken = method.getAnnotation(PassToken.class);
            if (passToken.required()) {
                return true;
            }
        }
        //剩下的接口全都需要登录
        //获取token
        String token = httpServletRequest.getHeader(JwtUtils.header);
        if (StringUtils.isEmpty(token)) {
            token = httpServletRequest.getParameter(JwtUtils.header);
        }
        if (StringUtils.isEmpty(token)) {
            String json = JSONUtils.toJSONString(R.error(401, "token为空", httpServletResponse));
            returnJson(httpServletResponse, json);
            return false;
        }
        Claims claims = null;
        try {
            claims = JwtUtils.getTokenClaim(token);
            if (claims == null || !claims.getSubject().equals("admin")) {
                String json = JSONUtils.toJSONString(R.error(403, "token过期，请重新登录", httpServletResponse));
                returnJson(httpServletResponse, json);
                return false;
            }
        } catch (Exception e) {
            String json = JSONUtils.toJSONString(R.error(401, "token错误", httpServletResponse));
            returnJson(httpServletResponse, json);
            return false;
        }
        //用户信息
        Admin admin = new Admin();
        Supplier supplier = new Supplier();
        supplier.setId(Integer.parseInt(claims.get("supplier").toString()));
        admin.setSupplier(supplier);
        admin.setId(Integer.parseInt(claims.get("id").toString()));
        admin.setUserType(Integer.parseInt(claims.get("userType").toString()));
        //验证是否需要账号权限
        if (method.isAnnotationPresent(SuperAdmin.class)) {
            SuperAdmin superAdmin = method.getAnnotation(SuperAdmin.class);
            //这个方法需要的权限数组
            String[] values = superAdmin.value();
            if (values != null && values.length != 0) {
                boolean emp = true; //是否没有权限
                for (String value : values) {
                    if (value.equals(admin.getUserType().toString())) {
                        emp = false;
                        break;
                    }
                }
                if (emp) {
                    //没有权限
                    String json = JSONUtils.toJSONString(R.error("你无权操作", httpServletResponse));
                    returnJson(httpServletResponse, json);
                    return false;
                }
            }
        }
        httpServletRequest.setAttribute("userInfo", admin);
        return true;

    }

    /*返回客户端数据*/
    private void returnJson(HttpServletResponse response, String json) throws Exception {
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print(json);
        } catch (IOException e) {
        } finally {
            if (writer != null)
                writer.close();
        }
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest,
                           HttpServletResponse httpServletResponse,
                           Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest,
                                HttpServletResponse httpServletResponse,
                                Object o, Exception e) throws Exception {
    }
}